<script setup name="testExamination">
import { ref, computed } from 'vue'
import { ElButton, ElCard, ElRadio, ElRadioGroup, ElAlert, ElInput, ElDialog, ElDescriptions, ElDescriptionsItem } from 'element-plus'
import { useRouter } from 'vue-router'
import { addPrivateExamination } from '@/api/privateExamination/privateExamination'
import { getDocTeamAndDoctor, createContract } from '@/api/contractHomepage/docContractHome'

// 获取基础URL用于图片显示
const baseUrl = import.meta.env.VITE_APP_BASE_API || ''

// 定义题目数据
const questions = ref([
  {
    id: 1,
    title: "您的身高体重指数(BMI)在正常范围内吗？",
    options: [
      { label: "BMI在18.5-24之间", value: 10 },
      { label: "BMI略高于或低于正常范围", value: 5 },
      { label: "BMI明显偏高或偏低", value: 1 }
    ]
  },
  {
    id: 2,
    title: "您的血压水平如何？",
    options: [
      { label: "血压正常(收缩压<120且舒张压<80)", value: 10 },
      { label: "血压略高(收缩压120-139或舒张压80-89)", value: 5 },
      { label: "血压偏高(收缩压≥140或舒张压≥90)", value: 1 }
    ]
  },
  {
    id: 3,
    title: "您的血糖水平如何？",
    options: [
      { label: "空腹血糖正常(<6.1mmol/L)", value: 10 },
      { label: "空腹血糖略高(6.1-7.0mmol/L)", value: 5 },
      { label: "空腹血糖偏高(≥7.0mmol/L)", value: 1 }
    ]
  },
  {
    id: 4,
    title: "您的胆固醇水平如何？",
    options: [
      { label: "总胆固醇正常(<5.2mmol/L)", value: 10 },
      { label: "总胆固醇略高(5.2-6.2mmol/L)", value: 5 },
      { label: "总胆固醇偏高(≥6.2mmol/L)", value: 1 }
    ]
  },
  {
    id: 5,
    title: "您的心率是否在正常范围内？",
    options: [
      { label: "静息心率60-100次/分钟", value: 10 },
      { label: "静息心率略快或略慢(50-59或101-110)", value: 5 },
      { label: "静息心率过快或过慢(<50或>110)", value: 1 }
    ]
  },
  {
    id: 6,
    title: "您的肺活量是否达标？",
    options: [
      { label: "肺活量达标(男性>3500ml,女性>2500ml)", value: 10 },
      { label: "肺活量接近达标", value: 5 },
      { label: "肺活量明显不足", value: 1 }
    ]
  },
  {
    id: 7,
    title: "您的睡眠质量如何？",
    options: [
      { label: "深度睡眠充足，无失眠", value: 10 },
      { label: "偶尔失眠，睡眠质量一般", value: 5 },
      { label: "经常失眠，睡眠质量差", value: 1 }
    ]
  },
  {
    id: 8,
    title: "您的体力状况如何？",
    options: [
      { label: "体力充沛，不易疲劳", value: 10 },
      { label: "体力一般，偶尔疲劳", value: 5 },
      { label: "体力不足，容易疲劳", value: 1 }
    ]
  },
  {
    id: 9,
    title: "您的免疫力如何？",
    options: [
      { label: "很少生病，恢复快", value: 10 },
      { label: "偶尔生病，恢复一般", value: 5 },
      { label: "经常生病，恢复慢", value: 1 }
    ]
  },
  {
    id: 10,
    title: "您的精神状态如何？",
    options: [
      { label: "精神饱满，情绪稳定", value: 10 },
      { label: "精神一般，偶有情绪波动", value: 5 },
      { label: "精神不振，情绪不稳定", value: 1 }
    ]
  }
])

// 用户答案
const answers = ref({})
// 体检感受描述
const examinationInfo = ref('')

// 计算总分
const totalScore = computed(() => {
  let score = 0
  for (const questionId in answers.value) {
    if (answers.value[questionId] !== undefined) {
      score += answers.value[questionId]
    }
  }
  return score
})

// 检查是否所有题目都已作答
const isAllAnswered = computed(() => {
  return Object.keys(answers.value).length === questions.value.length
})

// 路由实例
const router = useRouter()

// 弹窗相关
const dialogVisible = ref(false)
const recommendedTeam = ref({})

// 提交测试
const submitTest = () => {

  const data = {
    examinationScore: totalScore.value,
    examinationInfo: examinationInfo.value
  }
  
  addPrivateExamination(data).then(response => {
    // 根据总分推荐团队
    let teamId = null;
    if (totalScore.value < 30) {
      teamId = 4;
    } else if (totalScore.value >= 30 && totalScore.value < 50) {
      teamId = 18;
    } else if (totalScore.value >= 50 && totalScore.value < 80) {
      teamId = 9;
    } else if (totalScore.value >= 80 && totalScore.value <= 100) {
      teamId = 11;
    }
    if (teamId !== null) {
      getDocTeamAndDoctor(teamId).then(teamResponse => {
        if (teamResponse && teamResponse.data) {
          recommendedTeam.value = teamResponse.data
        } else {
          recommendedTeam.value = {}
        }
        console.log('设置推荐团队:', recommendedTeam.value)
        dialogVisible.value = true
      }).catch(error => {
        console.error('获取推荐团队信息失败:', error)
        recommendedTeam.value = {}
        dialogVisible.value = true // 即使获取团队信息失败，也显示弹窗
      })
    } else {
      // 没有推荐团队时直接显示弹窗
      recommendedTeam.value = {}
      dialogVisible.value = true
    }
    // 清空已填选项
    answers.value = {}
    examinationInfo.value = ''
  }).catch(error => {
    console.error('提交失败:', error)
  })
}

// 取消测试
const cancelTest = () => {
  router.push('/examination/privateExamination')
}

// 去到推荐的签约团队
const signTeam = () => {
  console.log('recommendedTeam:', recommendedTeam.value);
  if (recommendedTeam.value && recommendedTeam.value.teamId) {
    // 跳转到签约首页，并传递团队ID作为查询参数
    router.push({
      path: '/contractHomepage',
      query: {
        teamId: recommendedTeam.value.teamId
      }
    });
  } else {
    console.log('recommendedTeam或teamId为空');
  }
}
</script>

<template>
  <div class="test-container">
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>体检数据</span>
        </div>
      </template>

      <div class="questions-container">
        <el-card
            v-for="question in questions"
            :key="question.id"
            class="question-card"
            shadow="hover"
        >
          <div class="question-title">
            {{ question.id }}. {{ question.title }}
          </div>
          <el-radio-group
              v-model="answers[question.id]"
              class="options-container"
          >
            <el-radio
                v-for="option in question.options"
                :key="option.value"
                :label="option.value"
                class="option-item"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-card>
      </div>

      <div class="result-container">
        <el-alert
            v-if="isAllAnswered"
            :title="`当前总分: ${totalScore} 分 (满分100分，分数越高身体越健康)`"
            type="success"
            show-icon
            :closable="false"
        />
        <el-alert
            v-else
            title="请完成所有题目后再提交"
            type="warning"
            show-icon
            :closable="false"
        />
      </div>

      <!-- 体检感受描述 -->
      <div class="examination-info-container">
        <el-input
            v-model="examinationInfo"
            type="textarea"
            placeholder="请输入您的感受描述（非必填）"
            :rows="3"
            maxlength="200"
            show-word-limit
        />
      </div>

      <div class="button-container">
        <el-button
            type="primary"
            @click="submitTest"
            :disabled="!isAllAnswered"
            size="large"
        >
          提交测试
        </el-button>
        <el-button
            @click="cancelTest"
            size="large"
        >
          取消测试
        </el-button>
      </div>
    </el-card>

        <!-- 推荐团队弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="根据数据分数向您推荐以下团队"
        width="50%"
    >
      <div class="team-info-container">
        <!-- 团队图片展示 -->
        <div class="team-image-container" v-if="recommendedTeam.teamImg">
          <img :src="$urlImage + recommendedTeam.teamImg" alt="团队图片" class="team-image" v-if="recommendedTeam.teamImg"/>
        </div>
        <div class="team-image-container" v-else>
          <div class="no-image">暂无图片</div>
        </div>
        
        <el-descriptions
            :column="1"
            border
            class="team-details"
        >
          <el-descriptions-item label="团队名称">
            {{ recommendedTeam.teamName || '暂无信息' }}
          </el-descriptions-item>
          <el-descriptions-item label="团队描述">
            {{ recommendedTeam.teamInfo || '暂无信息' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="signTeam" v-if="recommendedTeam && recommendedTeam.teamId">去签约该团队</el-button>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.test-container {
  width: 100%;
  min-height: 100vh;
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  
  @media (max-width: 768px) {
    padding: 16px;
  }

  .test-card {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: none;
    overflow: hidden;
    
    .card-header {
      font-size: 24px;
      font-weight: 600;
      text-align: center;
      color: #303133;
      padding: 20px 0;
      background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
      color: white;
      margin: 0 -20px 20px -20px;
    }

    .questions-container {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
      
      @media (max-width: 768px) {
        grid-template-columns: 1fr;
      }

      .question-card {
        margin-bottom: 0;
        border-radius: 12px;
        border: 1px solid #e4e7ed;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 16px rgba(64, 158, 255, 0.15);
        }

        .question-title {
          font-size: 16px;
          font-weight: 600;
          margin-bottom: 16px;
          color: #303133;
          line-height: 1.5;
        }

        .options-container {
          display: flex;
          flex-direction: column;
          gap: 12px;

          .option-item {
            margin-right: 0;
            padding: 12px 16px;
            border-radius: 8px;
            transition: all 0.2s ease;
            
            &:hover {
              background-color: #f5f7fa;
            }
            
            &.is-checked {
              background-color: #ecf5ff;
              border-color: #409EFF;
            }
          }
        }
      }
    }

    .result-container {
      margin: 30px 0;
      
      .el-alert {
        border-radius: 8px;
        font-size: 16px;
        font-weight: 500;
      }
    }

    .examination-info-container {
      margin: 30px 0;
      
      .el-textarea {
        border-radius: 8px;
        
        .el-textarea__inner {
          border-radius: 8px;
          border: 1px solid #dcdfe6;
          transition: border-color 0.3s ease;
          
          &:focus {
            border-color: #409EFF;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
      }
    }

    .button-container {
      display: flex;
      justify-content: center;
      gap: 24px;
      margin-top: 40px;
      
      @media (max-width: 768px) {
        flex-direction: column;
        gap: 16px;
      }

      button {
        min-width: 160px;
        height: 48px;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &.el-button--primary {
          background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
          border: none;
          
          &:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);
          }
        }
        
        &:not(.el-button--primary) {
          border: 1px solid #dcdfe6;
          
          &:hover {
            border-color: #409EFF;
            color: #409EFF;
          }
        }
      }
    }
  }

  .team-info-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .team-image-container {
      width: 100%;
      display: flex;
      justify-content: center;
      margin: 10px 0 20px 0;
      
      .team-image {
        max-width: 100%;
        max-height: 300px;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        object-fit: cover;
      }
      
      .no-image {
        width: 100%;
        height: 300px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f7fa;
        border-radius: 12px;
        color: #909399;
        font-size: 16px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }
    
    .team-details {
      width: 100%;
      margin-top: 10px;
      
      :deep(.el-descriptions__label) {
        font-weight: bold;
        width: 100px !important;
      }
      
      :deep(.el-descriptions__content) {
        font-size: 14px;
      }
    }
  }
}
</style>
